//
//  BookingListController.m
//  whopaidforit
//
//  Created by Hoang Vu on 1/26/13.
//  Copyright (c) 2013 Hoang Vu. All rights reserved.
//

#import "BookingListController.h"

@interface BookingListController ()
@property(nonatomic,retain) UIView *popupView;
@property(nonatomic) NSInteger popupShow;

@end

@implementation BookingListController

@synthesize listData, tblItems, listNewUser, mailer;
@synthesize popupView,popupShow;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    return self;
}
- (void)viewDidLoad
{
    
    [super viewDidLoad];
    listData = [[NSMutableArray alloc] init];
    [self createNavigation];
    [self createPopUpView];
    [self loadData];
    [self changeStyle];
}
-(void) changeStyle
{
    [StyleControl background:self.view];
    self.tblItems.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tblItems.backgroundColor = [UIColor clearColor];
    self.tblItems.backgroundView = nil;
}
-(void) loadData
{
    Event *event = [Event instance];
    Entry * entry = [Entry instance];
    self.listData = [entry getDatasWS:event._id];
    if([listNewUser count]){
        NSMutableArray *email = [[NSMutableArray alloc] init];
        NSMutableArray *emailServer = [[NSMutableArray alloc] init];
        for(int i=0;i<[listNewUser count];i++)
        {
            ParticipateClass *par = [listNewUser objectAtIndex:i];
            if(par.idString){
                [emailServer addObject:par.firstMail];
            }else{
                [email addObject:par.firstMail];
            }
            
        }
        [email addObject:@"nguyenhoangvu29@gmail.com"];
        
        [self sendEmail:email];
    }
}

-(void)createNavigation
{
    Event *event = [Event instance];
    UIButton *left =[UIButton buttonWithType:UIButtonTypeCustom];
    [left setImage:[UIImage imageNamed:@"buttonlist"] forState:UIControlStateNormal];
    left.frame = CGRectMake(8, 8, 37, 35);
    [left addTarget:self action:@selector(leftButton:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *right =[UIButton buttonWithType:UIButtonTypeCustom];
    [right setImage:[UIImage imageNamed:@"popupShow"] forState:UIControlStateNormal];
    right.frame = CGRectMake(275, 8, 40, 35);
    
    [right addTarget:self action:@selector(rightButton:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [StyleControl  naviStyle:self.view andTitle:event._name andColor:0 andleftButton:left andRightButton:right borderLeft:1 borderRight:1];
}

-(IBAction)leftButton:(id)sender
{
    EventOverviewController *page=[[EventOverviewController alloc]init];
    [self presentModalViewController:page animated:YES];
    [page release];
}

-(IBAction)rightButton:(id)sender
{
    if(!popupShow)
    {
        [popupView setHidden:NO];
        popupShow=1;
        [self.tblItems setAlpha:0.3];
        [self.btAddBooking setAlpha:0.3];

    }
    else
    {
        [popupView setHidden:YES];
        popupShow=0;
        [self.tblItems setAlpha:1];
        [self.btAddBooking setAlpha:1];

    }
}

-(void)createPopUpView
{
    popupView =[[UIView alloc]initWithFrame:CGRectMake(120, 40, 200, 140)];
    UIImageView *locatoin=[[UIImageView alloc]initWithFrame:CGRectMake(160, 0, 25, 25)];
   
    
    UIView *popupContent =[[UIView alloc]initWithFrame:CGRectMake(15, 10, 180, 120)];
    [popupContent setBackgroundColor:[UIColor whiteColor]];
    [StyleControl setViewStyle:popupContent];
    [StyleControl drawLine:popupContent PositionX:0 PositionY:40 Width:180];
    [StyleControl drawLine:popupContent PositionX:0 PositionY:80 Width:180];


    UIView *menu1 =[[UIView alloc]initWithFrame:CGRectMake(0, 0, 180, 40)];
    [popupContent setBackgroundColor:[UIColor whiteColor]];
    
    UIView *menu2 =[[UIView alloc]initWithFrame:CGRectMake(0, 40 ,180, 40)];
    [popupContent setBackgroundColor:[UIColor whiteColor]];
    
    UIView *menu3 =[[UIView alloc]initWithFrame:CGRectMake(0, 80, 200, 40)];
    [popupContent setBackgroundColor:[UIColor whiteColor]];
    
    UILabel *menu1Label=[[UILabel alloc]initWithFrame:CGRectMake(45, 5, 100, 30)];
    menu1Label.text=@"Lijst beheren";
    [self tranferent:menu1Label];
    
    UILabel *menu2Label=[[UILabel alloc]initWithFrame:CGRectMake(45, 5, 100, 30)];
    menu2Label.text=@"Bewerken";
    [self tranferent:menu2Label];

    
    UILabel *menu3Label=[[UILabel alloc]initWithFrame:CGRectMake(45, 5, 100, 30)];
    menu3Label.text=@"Afrekenen";
    [self tranferent:menu3Label];

    UIImageView *menu1Image=[[UIImageView alloc]initWithFrame:CGRectMake(5, 5, 40, 40)];
    menu1Image.image=[UIImage  imageNamed:@"accept"];
    
    UIImageView *menu2Image=[[UIImageView alloc]initWithFrame:CGRectMake(5, 5, 30, 30)];
    menu2Image.image=[UIImage  imageNamed:@"spencil"];
    
    UIImageView *menu3Image=[[UIImageView alloc]initWithFrame:CGRectMake(5, 5, 25, 25)];
    menu3Image.image=[UIImage  imageNamed:@"afrek"];
    
    
    [StyleControl setBorderStyle:(UIImageView*)popupContent];
    [popupContent addSubview:menu1];
    [popupContent addSubview:menu2];
    [popupContent addSubview:menu3];
    
    [menu1 addSubview:menu1Label];
    [menu2 addSubview:menu2Label];
    [menu3 addSubview:menu3Label];
    
    [menu1 addSubview:menu1Image];
    [menu2 addSubview:menu2Image];
    [menu3 addSubview:menu3Image];


    [popupView addSubview:popupContent];
    [self.view addSubview:popupView];
    
    UITapGestureRecognizer  *tapGesture =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(popUpClick:)];
    [popupContent addGestureRecognizer:tapGesture];
    [tapGesture release];
    
    [popupView release];
    [popupContent release];
    [menu1 release];
    [menu2 release];
    [menu3 release];
    
    [menu1Label release];
    [menu2Label release];
    [menu3Label release];
    
    [menu1Image release];
    [menu2Image release];
    [menu3Image release];
    
    [popupView setHidden:1];


    locatoin.image=[UIImage imageNamed:@"location"];
    [popupView addSubview:locatoin];
    [locatoin release];
}

-(void)popUpClick:(UITapGestureRecognizer  *)gesture
{

    CGPoint  location = [gesture locationInView:gesture.view];
    if(location.y < 40)
    {
        EventDetailController *page=[[EventDetailController alloc]init];
        [self presentModalViewController:page animated:YES];
        [page release];
    }
    else if(location.y>40 &&location.y <80)
    {
        BookingDeleteController *page=[[BookingDeleteController alloc]init];
        [self presentModalViewController:page animated:YES];
        [page release];

    }
    else
    {
        CheckoutController *page=[[CheckoutController alloc]init];
        [self presentModalViewController:page animated:YES];
        [page release];

    }
}

-(void)tranferent:(UIView *)view
{
    [view setBackgroundColor:[UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:0]];
    
}

-(void)changStyle
{
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(IBAction)addBooking:(id)sender
{
    BookingAddController *detail = [[BookingAddController alloc] init];
    [self presentViewController:detail animated:YES completion:NULL];
    [detail release];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.listData count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 64;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BookingListCell *cell;
    cell = [[[BookingListCell alloc] initWithStyle:UITableViewCellSeparatorStyleNone reuseIdentifier:@"Cell"] autorelease];
    BookingClass *booking = [self.listData objectAtIndex:indexPath.row];
    ParticipateClass *par = [[ParticipateClass alloc] init];
    par.firstMail = booking.email;
    par.image = booking.picture;
    par.idString = booking.idString;
    cell.picture.image = [Helper getImageMember:par];
    cell.lblName.text = booking.bookingTitle;
    cell.lblDate.text = booking.bookingDate;
    cell.lblQuantity.text = [NSString stringWithFormat:@"%dx", booking.bookingQuantity];
    [StyleControl setPriceStyle:cell.lblPrice Price:booking.bookingPrice];
    //cell.lblPrice.text = [NSString stringWithFormat:@"$ %@", booking.bookingPrice];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Entry *entry  = [Entry instance];
    BookingClass *booking = [listData objectAtIndex:[indexPath row]];
    entry._id = booking.bookingId;
    BookingDetailController *detail = [[BookingDetailController alloc] init];
    [self presentViewController:detail animated:YES completion:NULL];
    [detail release];
}
- (void)dealloc {
    [super dealloc];
    [_btAddBooking release];
    [listData release];
}
- (void)viewDidUnload {
    [self setBtAddBooking:nil];
    [super viewDidUnload];
}
-(void) sendEmailServer:(NSMutableArray *) email
{
    BOOL first = YES;
    NSMutableString * listEmail = [[NSMutableString alloc] init];
    for (int i=0;i <[email count]; i++) {
        if(first){
            first = NO;
            listEmail = [email objectAtIndex:i];
        }else{
            [listEmail appendString:[NSString stringWithFormat:@",%@",[email objectAtIndex:i] ] ];
        }
    }
    //User *user = [User instance];
    //user. send email by server
}
-(void) sendEmail:(NSMutableArray *) email
{
    if ([MFMailComposeViewController canSendMail])
    {
        //User *user =[User instance];
        Event *event = [Event instance];
        mailer = [[MFMailComposeViewController alloc] init];
        mailer.mailComposeDelegate = self;
        [mailer setSubject:@"Uitnodiging om WhoPaidForIt te gebruiken"];
        //NSArray *toRecipients = [NSArray arrayWithObjects:email, nil];
        [mailer setToRecipients:email];
        //UIImage *myImage = [UIImage imageNamed:@"mobiletuts-logo.png"];
        //NSData *imageData = UIImagePNGRepresentation(myImage);
        //[mailer addAttachmentData:imageData mimeType:@"image/png" fileName:@"mobiletutsImage"];
        NSString *emailBody = [NSString stringWithFormat:@"<p>Beste,</p><p>You nodigt u uit om de WhoPaidForIt app te downloaden en te participeren in het Event %@.</p><p>Met de WhoPaidForIt app administreert u snel en eenvoudig gezamenlijke uitgaven. De app verrekent vervolgens de gezamenlijke kosten naar kosten per deelnemer aan een event.</p><br/><p>[Logo Apple AppStore link to whopaidforit app]<br/>[Logo Google Play Store link to whopaidforit app]</p>", event._name ];
        [mailer setMessageBody:emailBody isHTML:YES];
        [self presentModalViewController:mailer animated:YES];
        [mailer release];
        
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failure"
                                                        message:@"Your device doesn't support the composer sheet"
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
}
-(void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    //UIViewController * parent = [self.view containingViewController];
    //[self becomeFirstResponder];
    [self dismissModalViewControllerAnimated:YES];
    /*if ([parent respondsToSelector:@selector(dismissSemiModalView)]) {
     [parent dismissSemiModalView];
     }*/
}
@end
